package com.example.newseconddemo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.newseconddemo.R;
import com.example.newseconddemo.bean.ImagesBean;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 测试HandlerThread与普通Thread+handler,弱引用等
 */
public class HomeActivity extends AppCompatActivity {
    ImagesBean imagesBean;//图片类

    ImageView imageView1;//普通Thread+handler+回调
    ImageView imageView2;//普通线程：弱引用+handler
    ImageView imageView3;// HandlerThread+handler

    MyHandler2 myHandler2 = new MyHandler2(this);  //使用静态内部类+弱引用
    MyHandler3 myhandler3 = new MyHandler3(this);  //使用静态内部类+弱引用

    Handler handler3;// HandlerThread+handler，用以启动线程

    HandlerThread handlerThread;// HandlerThread


    private String url[] = {
            "https://img-blog.csdn.net/20160903083245762",
            "https://img-blog.csdn.net/20160903083252184",
            "https://img-blog.csdn.net/20160903083257871",
            "https://img-blog.csdn.net/20160903083257871",
            "https://img-blog.csdn.net/20160903083311972",
            "https://img-blog.csdn.net/20160903083319668",
            "https://img-blog.csdn.net/20160903083326871"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        imageView1 = findViewById(R.id.image1);
        imageView2 = findViewById(R.id.image2);
        imageView3 = findViewById(R.id.image3);

        //普通线程+handler+回调
        new Thread(() -> {
            imagesBean = new ImagesBean();
            Message message = new Message();
            Bitmap bitmaps = downloadUrlBitmap("https://img-blog.csdn.net/20160903083245762");
            imagesBean.bitmap = bitmaps;
            message.obj = imagesBean;
            handler1.sendMessage(message);
        }).start();

        //普通线程：弱引用+handler
        new Thread(() -> {
            imagesBean = new ImagesBean();
            Message message = new Message();
            Bitmap bitmaps = downloadUrlBitmap("https://img-blog.csdn.net/20160903083245762");
            imagesBean.bitmap = bitmaps;
            message.obj = imagesBean;
            myHandler2.sendMessage(message);
        }).start();

        // HandlerThread线程：HandlerThread+handler
        handlerThread = new HandlerThread("downloadImage");
        //必须先开启线程
        handlerThread.start();
        //子线程Handler
        handler3 = new Handler(handlerThread.getLooper(), new MyChildHandler3());
        for (int i = 0; i < 7; i++) {
            //每个1秒去更新图片
            handler3.sendEmptyMessageDelayed(i, 1000 * i);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler1.removeCallbacksAndMessages(null);
    }

    //普通线程+handler+回调：使用回调
    private final Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.obj != null) {
                ImagesBean imagesBeans = (ImagesBean) msg.obj;
                imageView1.setImageBitmap(imagesBeans.bitmap);
            }
            return false;
        }
    });

    /**使用静态内部类+弱引用*/
    static class MyHandler2 extends Handler {
        WeakReference<HomeActivity> myActivity;

        public MyHandler2(HomeActivity activity) {
            myActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {

            if (msg.obj != null) {
                ImagesBean imagesBeans = (ImagesBean) msg.obj;
                myActivity.get().imageView2.setImageBitmap(imagesBeans.bitmap);
            }
        }
    }

    /**使用静态内部类+弱引用*/
    static class MyHandler3 extends Handler {

        WeakReference<HomeActivity> myActivity;

        public MyHandler3(HomeActivity activity) {
            myActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(android.os.Message msg) {

            if (msg.obj != null) {
                ImagesBean imagesBeans = (ImagesBean) msg.obj;
                myActivity.get().imageView3.setImageBitmap(imagesBeans.bitmap);
            }
        }
    }




    /**实现回调接口，处理HandlerThread的逻辑*/
    class MyChildHandler3 implements Handler.Callback {
        @Override
        public boolean handleMessage(Message msg) {
            //子线程
//            Bitmap bitmap=downloadUrlBitmap(url[msg.what]);
//            ImagesBean imageModel=new ImagesBean();
//            imageModel.bitmap=bitmap;
//            Message msg1 = new Message();
//            msg1.obj =imageModel;
//            //发送消息给主线程，更改UI
//            myhandler3.sendMessage(msg1);


//            Bitmap bitmap=downloadUrlBitmap(url[msg.what]);
//            imageView3.setImageBitmap(bitmap);

//            imageView3.setImageResource(R.drawable.duola);


            return false;
        }
    }


    //借用一下
    private Bitmap downloadUrlBitmap(String urlString) {
        HttpURLConnection urlConnection = null;
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }


}